﻿using AntdUI;
using Azure;
using DataCollection.Core.Models;
using DataCollection.Infrastructure;
using Dm.util;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using Mapster;
using Masuit.Tools.Database;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DataCollection.WinForm.Forms
{
    public partial class HistoryForm : DCBaseForm
    {
        #region 属性

        /// <summary>
        /// Excel路径
        /// </summary>
        private string ExcelPath = string.Empty;

        #endregion

        #region 自定义方法

        /// <summary>
        /// 布局
        /// </summary>
        private void SetupForm()
        {
            ListTable.Columns = new AntdUI.ColumnCollection {
                new AntdUI.Column("Number","试压记录编号",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("ProjectNumber","项目编号",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("ProjectName","项目名称",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("StartTime","开始时间",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("EndTime","结束时间",AntdUI.ColumnAlign.Center),
                new AntdUI.Column("Operation","点位数据",AntdUI.ColumnAlign.Center)
            };
        }

        /// <summary>
        /// 列表
        /// </summary>
        public void LoadList()
        {
            Dictionary<string, object> where = new Dictionary<string, object>();
            List<HistoryModel> list = HistoryModel.List(where);
            List<HistoryItem> itemList = new List<HistoryItem>();
            foreach (HistoryModel model in list)
            {
                HistoryItem item = new HistoryItem();
                model.Adapt(item);
                itemList.Add(item);
            }
            ListTable.DataSource = itemList;
        }

        private void ExportPointData(string number, string name)
        {
            Dictionary<string, object> where = new Dictionary<string, object>();
            where["history_number"] = number;

            string[] head2 = ["试压记录编号", "近端压力", "远端压力", "添加时间"];
            DCSpin(this, "导出数据...", (action) =>
            {
                System.Data.DataTable table = HistoryDataModel.List(where).Select(x => new { x.HistoryNumber, x.MainPressure, x.RemotePressure, x.Time }).ToDataTable();
                string excelName = string.Format("CollectReport/{0}.xlsx", number);
                ExcelPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, excelName);
                ExportExcel(table, ExcelPath, head2);
            }, null, () => {
                string destinationFilePath = Path.Combine(Singleton.ExportPath, string.Format("{0}-{1}试压数据.xlsx", name,number));
                if (File.Exists(ExcelPath))
                {
                    if (!File.Exists(destinationFilePath))
                    {
                        File.Move(ExcelPath, destinationFilePath);
                    }
                    SuccessNotification("试压数据已导出");
                }
                else
                {
                    ErrorNotification("导出失败");
                }
                Singleton.Instance.ReloadReportList();
            });

        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="filePath"></param>
        /// <param name="head"></param>
        public static void ExportExcel(System.Data.DataTable dataTable, string filePath, string[]? head)
        {
            var spreadsheetDocument = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook);
            using (spreadsheetDocument)
            {
                var workbookPart = spreadsheetDocument.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();

                var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                var sheetData = new SheetData();
                worksheetPart.Worksheet = new Worksheet(sheetData);

                var sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());

                var sheet = new Sheet()
                {
                    Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
                    SheetId = 1,
                    Name = "Sheet1"
                };
                sheets.Append(sheet);


                var headerRow = new Row();
                if (head is not null)
                {
                    foreach (string title in head)
                    {
                        var cell = new Cell();
                        cell.DataType = CellValues.String;
                        cell.CellValue = new CellValue(title);
                        headerRow.AppendChild(cell);
                    }
                }
                else
                {
                    foreach (DataColumn column in dataTable.Columns)
                    {
                        var cell = new Cell();
                        cell.DataType = CellValues.String;
                        cell.CellValue = new CellValue(column.ColumnName);
                        headerRow.AppendChild(cell);
                    }
                }

                sheetData.AppendChild(headerRow);

                foreach (DataRow row in dataTable.Rows)
                {
                    var dataRow = new Row();

                    for (int i = 0; i < dataTable.Columns.Count; i++)
                    {
                        DataColumn column = dataTable.Columns[i];
                        var cell = new Cell();
                        cell.DataType = CellValues.String;
                        string? value = row[column].ToString();
                        if (value is not null)
                        {
                            cell.CellValue = new CellValue(value);
                        }
                        else
                        {
                            cell.CellValue = new CellValue("");
                        }

                        if (i == dataTable.Columns.Count -1)
                        {
                            if (value is not null)
                            {
                                long timeStamp = long.Parse(value);
                                DateTime time = Util.ConvertToDateTime(timeStamp);
                                cell.CellValue = new CellValue(time.ToString("yyyy-MM-dd HH:mm:ss"));
                            }
                        }
                        
                        dataRow.AppendChild(cell);
                    }
                    sheetData.AppendChild(dataRow);
                }
            }
        }

        #endregion

        #region 系统事件
        public HistoryForm()
        {
            InitializeComponent();
            Header.Text = "历史记录";
            FullScreen = true;
        }

        private void HistoryForm_Load(object sender, EventArgs e)
        {
            SetupForm();
            DCSpin(this, "加载数据...", (action) =>
            {
                LoadList();
            }, null, () => { });

        }
        #endregion

        private void ListTable_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            if (e.Record is HistoryItem data)
            {
                CellLink link = e.Btn;
                if (link.Id == "export")
                {
                    AntdUI.Modal.open(new AntdUI.Modal.Config(this, "友情提示", "导出时不要执行其他操作，请耐心等待。")
                    {
                        OnOk = config =>
                        {
                            Thread.Sleep(100);
                            ExportPointData(data.Number,data.ProjectName);
                            return true;
                        },
                    });

                    //HistoryDataForm frm = new HistoryDataForm();
                    //frm.SelectHistoryNumber = data.Number;
                    //frm.ShowDialog();
                }
            }
        }
    }
}
